package top.cardone.security.shiro.web.filter.authc.impl;

import com.google.gson.Gson;
import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.CharEncoding;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import top.cardone.context.ApplicationContextHolder;
import top.cardone.context.util.CodeExceptionUtils;
import top.cardone.security.shiro.authc.impl.OAuth2TokenImpl;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Writer;
import java.util.Map;

/**
 * Created by Administrator on 2016/2/4.
 */
@Log4j2
public class OAuth2FilterImpl extends AuthenticatingFilter {
    @Setter
    protected String credentialsParam = "token";

    @Setter
    protected String principalParam = "username";

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        String accessToken = httpRequest.getHeader(credentialsParam);

        if (StringUtils.isBlank(accessToken)) {
            accessToken = request.getParameter(credentialsParam);
        }

        String principal = httpRequest.getHeader(principalParam);

        if (StringUtils.isBlank(principal)) {
            principal = request.getParameter(principalParam);
        }

        OAuth2TokenImpl oAuth2Token = new OAuth2TokenImpl();

        oAuth2Token.setCredentials(accessToken);

        oAuth2Token.setPrincipal(principal);

        return oAuth2Token;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);

        if (!subject.isAuthenticated()) {
            return executeLogin(request, response);
        }

        return true;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        if (!StringUtils.startsWith(request.getContentType(), org.springframework.http.MediaType.APPLICATION_JSON_VALUE)) {
            return super.onLoginFailure(token, e, request, response);
        }

        response.setCharacterEncoding(CharEncoding.UTF_8);
        response.setContentType(org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE);

        Map<String, String> errorInfo;

        try (Writer out = response.getWriter()) {
            String requestURI = getPathWithinApplication(request);

            if (e instanceof IncorrectCredentialsException) {
                errorInfo = CodeExceptionUtils.newMap(requestURI, "000004", "授权不合法");
            } else {
                errorInfo = CodeExceptionUtils.newMap(requestURI, e);
            }

            String json = ApplicationContextHolder.getBean(Gson.class).toJson(errorInfo);

            out.write(json);
        } catch (java.io.IOException ex) {
            log.error(ex.getMessage(), ex);
        }

        return false;
    }
}
